<template>
  <div class="tab-dialog-box pos-abs">
    <el-tabs v-model="activeTab" :before-leave="onTabChange">
      <el-tab-pane label="密码策略" name="passwordPolicy">
        <div class="tab-content-box pos-abs">
          <el-form
            :model="passwordPolicy"
            label-width="130px"
            :size="layoutStore.defaultFormItemSize"
            class="setting-form"
          >
            <!-- 密码定期更新 -->
            <el-form-item label="密码定期更新">
              <el-switch v-model="passwordPolicy.passwordExpired" />
            </el-form-item>
            <template v-if="passwordPolicy.passwordExpired">
              <el-form-item label="更新周期">
                <el-input v-model.number="passwordPolicy.updateInterval" type="number">
                  <template #append>天</template>
                </el-input>
              </el-form-item>
            </template>

            <!-- 密码强度限制 -->
            <el-form-item label="密码强度限制">
              <el-switch v-model="passwordPolicy.passwordComplexity" />
            </el-form-item>
            <template v-if="passwordPolicy.passwordComplexity">
              <el-form-item class="rule-form-item">
                <div class="rule-item">
                  <el-checkbox v-model="passwordPolicy.minLengthEnabled">最小长度</el-checkbox>
                  <el-input
                    style="width: 146px"
                    v-model.number="passwordPolicy.minLength"
                    type="number"
                  >
                    <template #append>位</template>
                  </el-input>
                </div>
                <div class="rule-list">
                  <el-checkbox v-model="passwordPolicy.includeDigit">包含数字</el-checkbox>
                  <el-checkbox v-model="passwordPolicy.includeLowerCase">包含小写字母</el-checkbox>
                  <el-checkbox v-model="passwordPolicy.includeUpperCase">包含大写字母</el-checkbox>
                  <el-checkbox v-model="passwordPolicy.includeSpecialChar">包含字符</el-checkbox>
                </div>
              </el-form-item>
            </template>

            <!-- 禁用旧密码 -->
            <el-form-item label="禁用旧密码">
              <el-switch v-model="passwordPolicy.banOldPassword" />
            </el-form-item>
            <template v-if="passwordPolicy.banOldPassword">
              <el-form-item label="禁用个数">
                <el-input v-model.number="passwordPolicy.banOldPasswordCount" type="number">
                  <template #append>个</template>
                </el-input>
              </el-form-item>
            </template>

            <!-- 修改初始密码提醒 -->
            <el-form-item label="修改初始密码提醒">
              <el-switch v-model="passwordPolicy.modifyInitPassword" />
            </el-form-item>

            <!-- 新用户默认密码 -->
            <el-form-item label="新用户默认密码">
              <el-input v-model="passwordPolicy.initPassword" show-password />
            </el-form-item>

            <!-- 保存按钮 -->
            <el-form-item>
              <el-button type="primary" @click="savePasswordPolicy" :loading="loading"
                >保存设置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <el-tab-pane label="登录策略" name="loginPolicy">
        <div class="tab-content-box pos-abs">
          <el-form
            :model="loginPolicy"
            label-width="120px"
            :size="layoutStore.defaultFormItemSize"
            class="setting-form"
          >
            <!-- 排他登录 -->
            <el-form-item label="排他登录">
              <el-switch v-model="loginPolicy.excludeLogin" />
              <div class="error-handle-desc">开启后同一账号只能在一处登录</div>
            </el-form-item>

            <!-- Jie. 20250802 超时延期 -->
            <el-form-item label="超时延期">
              <el-switch v-model="loginPolicy.timeoutExtend" />
              <div class="error-handle-desc">开启后操作过程中可延长登录时间</div>
            </el-form-item>

            <!-- 登录超时 -->
            <el-form-item label="登录超时">
              <el-input v-model.number="loginPolicy.loginTimeout" type="number">
                <template #append>分钟</template>
              </el-input>
            </el-form-item>

            <!-- 密码错误次数 -->
            <el-form-item label="密码错误次数" class="no-margin-bottom">
              <el-input v-model.number="loginPolicy.passwordErrorCount" type="number">
                <template #append>次</template>
              </el-input>
            </el-form-item>
            <!-- 错误处理方式 -->
            <el-form-item :class="{ 'no-margin-bottom': loginPolicy.delayLoginWhenError }">
              <div class="error-handle-desc">
                输入密码错误将进行处理，设置3以下值表示不启动该功能
              </div>
              <el-radio-group v-model="loginPolicy.delayLoginWhenError">
                <el-radio :label="false">账号锁定</el-radio>
                <el-radio :label="true">延时登录</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 延迟时间 -->
            <el-form-item
              :class="{ 'no-margin-bottom': !loginPolicy.delayLoginWhenError }"
              label="延迟时间"
              v-if="loginPolicy.delayLoginWhenError"
              style="margin-left: 70px"
            >
              <el-input v-model.number="loginPolicy.delayLoginTime" type="number">
                <template #append>分钟</template>
              </el-input>
            </el-form-item>

            <!-- 保存按钮 -->
            <el-form-item class="login-save-btn">
              <el-button type="primary" @click="saveLoginPolicy" :loading="loading"
                >保存设置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <!-- Jie. 20250804 增加常用话术 -->
      <el-tab-pane label="常用话术" name="commonExpressions">
        <div class="tab-content-box pos-abs">
          <div class="param-header">
            <el-button type="primary" @click="onAddExpression" :loading="loading">
              添加话术
            </el-button>
          </div>
          <vxe-table
            :data="commonExpressions"
            show-overflow="title"
            show-header-overflow="title"
            :row-config="{ height: 35, isHover: true }"
            height="400px"
          >
            <vxe-column type="seq" title="序号" width="60" drag-sort />
            <vxe-column title="话术内容" field="content">
              <template #default="{ row }">
                <el-input
                  v-model="row.content"
                  placeholder="请输入话术内容"
                  maxlength="500"
                  show-word-limit
                />
              </template>
            </vxe-column>
            <vxe-column title="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button link type="danger" @click="onDeleteExpression(row)"> 删除 </el-button>
              </template>
            </vxe-column>
            <template #empty>
              <div class="table-empty unified-font">
                <img src="@/assets/img/empty.png" />
                <span>暂无数据</span>
              </div>
            </template>
          </vxe-table>

          <!-- 保存按钮 -->
          <el-form-item style="margin-top: 24px">
            <el-button type="primary" @click="saveCommonExpressions" :loading="loading">
              保存设置
            </el-button>
          </el-form-item>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formSysConf',
};
</script>

<script setup lang="ts">
import { SysConfController } from '@/api/system';
import { usePermissions } from '@/common/hooks/usePermission';
// Jie. 20250804 增加常用话术
import { useLayoutStore } from '@/store';
import { CommonExpression, SysConfLoginPolicy, SysConfPasswordPolicy } from '@/types/upms/sysconf';
import { ElMessage, ElMessageBox, TabPaneName } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

const layoutStore = useLayoutStore();
const { checkPermCodeExist } = usePermissions();
const activeTab = ref('passwordPolicy');
const loading = ref(false);

// 密码策略数据
const passwordPolicy = reactive<SysConfPasswordPolicy>({
  passwordExpired: false,
  updateInterval: 90,
  passwordComplexity: false,
  minLengthEnabled: false,
  minLength: 8,
  includeDigit: false,
  includeLowerCase: false,
  includeUpperCase: false,
  includeSpecialChar: false,
  banOldPassword: false,
  banOldPasswordCount: 3,
  modifyInitPassword: false,
  initPassword: '123456',
});

// 登录策略数据
const loginPolicy = reactive<SysConfLoginPolicy>({
  excludeLogin: false,
  loginTimeout: 30,
  passwordErrorCount: 5,
  delayLoginWhenError: false,
  delayLoginTime: 30,
  // Jie. 20250802 超时延期
  timeoutExtend: false,
});

// Jie. 20250804 常用话术数据
const commonExpressions = ref<CommonExpression[]>([]);

// 加载配置数据
const loadConfData = async (confCode: 'passwordPolicy' | 'loginPolicy' | 'commonExpressions') => {
  try {
    loading.value = true;
    const res = await SysConfController.getSysConf({ confCode });

    if (res.data?.conf) {
      if (confCode === 'passwordPolicy') {
        const pwdPolicy = JSON.parse(res.data.conf) as SysConfPasswordPolicy;
        Object.assign(passwordPolicy, pwdPolicy);
      } else if (confCode === 'loginPolicy') {
        const loginPol = JSON.parse(res.data.conf) as SysConfLoginPolicy;
        Object.assign(loginPolicy, loginPol);
      } else if (confCode === 'commonExpressions') {
        const confData = JSON.parse(res.data.conf);
        // Jie. 20250804 如果是空对象 {} 或者其他非数组类型，则初始化为空数组
        if (Array.isArray(confData)) {
          commonExpressions.value = confData;
        } else {
          commonExpressions.value = [];
        }
      }
    } else if (confCode === 'commonExpressions') {
      // 如果没有配置数据，初始化空数组
      commonExpressions.value = [];
    }
  } catch (error) {
    console.error(`加载${getConfigName(confCode)}配置失败:`, error);
    ElMessage.error(`加载${getConfigName(confCode)}配置失败`);
    if (confCode === 'commonExpressions') {
      commonExpressions.value = [];
    }
  } finally {
    loading.value = false;
  }
};

// Jie. 20250804 获取配置名称
const getConfigName = (confCode: string) => {
  switch (confCode) {
    case 'passwordPolicy':
      return '密码策略';
    case 'loginPolicy':
      return '登录策略';
    case 'commonExpressions':
      return '常用话术';
    default:
      return '';
  }
};

// 保存密码策略
const savePasswordPolicy = async () => {
  try {
    await ElMessageBox.confirm('确认要保存密码策略配置吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    loading.value = true;
    await SysConfController.updateSysConf({
      sysConfDto: {
        confCode: 'passwordPolicy',
        conf: JSON.stringify(passwordPolicy),
      },
    });
    ElMessage.success('密码策略保存成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存密码策略失败:', error);
      ElMessage.error('保存密码策略失败');
    }
  } finally {
    loading.value = false;
  }
};

// 保存登录策略
const saveLoginPolicy = async () => {
  try {
    await ElMessageBox.confirm('确认要保存登录策略配置吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    loading.value = true;
    await SysConfController.updateSysConf({
      sysConfDto: {
        confCode: 'loginPolicy',
        conf: JSON.stringify(loginPolicy),
      },
    });
    ElMessage.success('登录策略保存成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存登录策略失败:', error);
      ElMessage.error('保存登录策略失败');
    }
  } finally {
    loading.value = false;
  }
};

// Jie. 20250804 保存常用话术
const saveCommonExpressions = async () => {
  try {
    // 验证话术内容
    const invalidExpressions = commonExpressions.value.filter(item => !item.content.trim());
    if (invalidExpressions.length > 0) {
      ElMessage.error('存在空的话术内容，请填写完整后再保存');
      return;
    }

    await ElMessageBox.confirm('确认要保存常用话术配置吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    loading.value = true;
    await SysConfController.updateSysConf({
      sysConfDto: {
        confCode: 'commonExpressions',
        conf: JSON.stringify(commonExpressions.value),
      },
    });
    ElMessage.success('常用话术保存成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存常用话术失败:', error);
      ElMessage.error('保存常用话术失败');
    }
  } finally {
    loading.value = false;
  }
};

// Jie. 20250804 添加话术
const onAddExpression = () => {
  commonExpressions.value.push({
    content: '',
  });
};

// Jie. 20250804 删除话术
const onDeleteExpression = async (row: CommonExpression) => {
  try {
    await ElMessageBox.confirm(`确认要删除这条话术吗？\n"${row.content}"`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const index = commonExpressions.value.indexOf(row);
    if (index > -1) {
      commonExpressions.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  } catch (error) {
    // 用户取消删除，不做任何操作
  }
};

// Tab切换处理
const onTabChange = async (newTab: TabPaneName) => {
  if (newTab === activeTab.value) return true;
  await loadConfData(newTab as 'passwordPolicy' | 'loginPolicy' | 'commonExpressions');
  return true;
};

// 初始化
onMounted(() => {
  loadConfData('passwordPolicy');
});
</script>

<style lang="scss" scoped>
.pos-abs {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.tab-dialog-box {
  padding: 0 !important;
  margin: 0 !important;

  :deep(.el-tabs__header) {
    margin-bottom: 0;
    background-color: white;
    border-top: 1px solid #e8e8e8;
  }

  :deep(.el-tabs__content) {
    position: absolute;
    top: 44px;
    left: 0;
    right: 0;
    bottom: 0;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  :deep(.el-tabs__item) {
    height: 44px;
    line-height: 44px;
  }

  :deep(.el-tabs__nav-wrap) {
    padding-left: 24px;
  }

  :deep(.el-tabs__content) {
    overflow: hidden;
  }

  .tab-content-box {
    display: flex;
    margin: 16px;
    flex-direction: column;
    background-color: #fff;
    padding: 24px;
    border-radius: 2px;
    overflow: auto;
  }
}

.no-margin-bottom {
  margin-bottom: 10px !important;
}

.error-handle-desc {
  color: #999;
  font-size: 14px;
}

.login-save-btn {
  // margin-top: 24px !important;
}

.setting-form {
  max-width: 600px;

  :deep(.el-form-item) {
    margin-bottom: 24px;
  }

  :deep(.el-input) {
    width: 240px;

    .el-input-group__append {
      background-color: #fff;
      padding: 0 10px;
    }
  }

  :deep(.el-switch) {
    margin-right: 8px;
  }

  :deep(.el-radio-group) {
    .el-radio {
      margin-right: 24px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.rule-form-item :deep(.el-form-item__content) {
  display: flex;
  align-items: start;
  flex-direction: column;
}

.rule-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .el-checkbox {
    margin-right: 16px;
  }
}

.rule-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// Jie. 20250804 添加常用话术
.param-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 16px;
}

.param-title {
  font-size: 16px;
  font-weight: bold;
}

.table-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.table-empty img {
  width: 100px;
  height: 100px;
  margin-bottom: 8px;
}
</style>
